<?php namespace sacvoyage\storage;

require_once('sacvoyage/Object.php');
use \sacvoyage\Object;

require_once('sacvoyage/Pathfinder.php');
use \sacvoyage\Pathfinder;

require_once('sacvoyage/storage/util.php');

/*
 * writes document obtained from documentIterator to table
 *
 */
class Writer {

	public function __construct(&$table, &$documentIterator) {
		$this->_table=&$table;
		$this->_documentIterator=&$documentIterator;
	}

	public function go() {
		// TODO: split rows into 10000-packets\
		$count=0;
		$insertValues=array();
		foreach($this->_documentIterator as $document) {
			$finder=new Pathfinder($document);
			$_id=$this->_table->escape($finder['._id']);
			$_rev=$this->_table->escape($finder['._rev']);
			
			foreach($finder as $path=>$value) {
				$type=json_typeof($value);
				// evaluate value's type-name
				if(is_string($value) || in_array($path, array('._id', '._rev'))) {
					$type='string';
				} elseif(is_numeric($value)) {
					$type='number';
				} elseif(is_bool($value))    {
					$type='boolean';
					$value=$value ? 'true' : 'false';
				} elseif(is_null($value)) {
					$type='null';
					$value='null';
				} else {
					throw new Exception('value to cannot be '.$type);
				}
			
				$value=$this->_table->escape($value);
				$path=$this->_table->escape($path);
				$insertValues[]="('$_id', '$_rev', '$path', '$type', '$value')";
				$count++;
			}
		}
		if($insertValues) {
			$this->_table->query(
				"INSERT INTO {$this->_table->getExpression()} ".
				"(_id, _rev, path, type, value) ".
				"VALUES ".implode(', ', $insertValues)
			);
		}
		return $count;
	}


};
